//
//  MeView.swift
//  CMB250716
//
//  Created by Andy Lau on 2024/7/16.
//

import SwiftUI
import Foundation

struct MeView: View {
    @EnvironmentObject var dataManager: DataManager
    @State private var showingCoupons = false
    @State private var showingSettings = false
    @State private var showingSecuritySettings = false
    @State private var showingUnifiedProfile = false
    
    @State private var showingMembershipPolicy = false
    @State private var showingInviteTest = false
    
    // MARK: - 社交媒体提交逻辑
    @StateObject private var socialMediaManager = SocialMediaManager()
    @State private var showingImagePicker = false
    @State private var showingSubmissionSheet = false
    @State private var selectedPlatform: SocialPlatform?
    @State private var submissionDescription = ""
    @State private var submissionLink = ""
    @State private var selectedImage: UIImage?
    @State private var showingSubmissionAlert = false
    @State private var submissionAlertMessage = ""
    @State private var submissionType: SubmissionType = .link
    @State private var showingSocialMediaDetail = false
    
    enum SubmissionType {
        case link
        case image
    }

    
    // 计算属性：当前语言
    private var language: String {
        return dataManager.currentLanguage
    }
     
     var body: some View {
        VStack(spacing: 0) {
            // 顶部导航
            topNavigation
            
            if let user = dataManager.currentUser {
                ScrollView {
                    VStack(spacing: 10) {
                        // 会员信息卡片
                        memberInfoCard(user: user)
                        
                        // 会员制度与积分使用规则
                        membershipPolicyCard
                        
                        // 积分概览
                        pointsOverview(user: user)
                        
                        // 社交媒体Logo
                        socialMediaLogos
                        
                        // 社交互动
                        socialInteractionCard(user: user)
                        
                        // 我的优惠券（独立一行）
                        myCouponsCard
                        
                        // 功能菜单（移除我的优惠券）
                        functionsMenu
                        
                        // 会员特权（已移除）
                        // memberBenefits
                    }
                    .padding(.horizontal, 20)
                    .padding(.bottom, 100)
                }
            } else {
                // 未登录状态
                guestView
            }
        }
        .background(
            LinearGradient(
                colors: AppTheme.Colors.backgroundGradient,
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .ignoresSafeArea()
        )
        .sheet(isPresented: $showingCoupons) {
            MyCouponsView()
                .environmentObject(dataManager)
        }
        .sheet(isPresented: $showingSettings) {
            SettingsView()
                .environmentObject(dataManager)
        }
        .sheet(isPresented: $showingSecuritySettings) {
            SecuritySettingsView()
                .environmentObject(dataManager)
        }
        .sheet(isPresented: $showingUnifiedProfile) {
            UnifiedProfileView()
                .environmentObject(dataManager)
        }

        .sheet(isPresented: $showingMembershipPolicy) {
            MembershipPolicyDetailView()
                .environmentObject(dataManager)
        }
        .sheet(isPresented: $showingInviteTest) {
            InviteView()
                .environmentObject(dataManager)
        }

        .alert(isPresented: $dataManager.showingCouponUnlockNotification) {
            Alert(
                title: Text(dataManager.currentLanguage == "zh" ? AppStrings.Coupons.couponUnlocked : AppStrings.Coupons.couponUnlockedEn),
                message: Text(dataManager.couponUnlockNotificationMessage),
                dismissButton: .default(Text(dataManager.currentLanguage == "zh" ? AppStrings.Common.confirm : AppStrings.Common.confirmEn))
            )
        }
        .alert(isPresented: $showingSubmissionAlert) {
            Alert(
                title: Text(language == "zh" ? "提交状态" : "Submission Status"),
                message: Text(submissionAlertMessage),
                dismissButton: .default(Text(language == "zh" ? "确定" : "OK"))
            )
        }
        .sheet(isPresented: $showingImagePicker) {
            ImagePicker { image in
                handleImageSelection(image: image)
            }
        }
        .sheet(isPresented: $showingSubmissionSheet) {
            socialMediaSubmissionSheet
        }
        .sheet(isPresented: $showingSocialMediaDetail) {
            if let user = dataManager.currentUser {
                SocialMediaDetailView(user: user)
                    .environmentObject(dataManager)
                    .environmentObject(socialMediaManager)
            }
        }
        .onChange(of: dataManager.shouldNavigateToAllCoupons) { shouldNavigate in
            if shouldNavigate {
                showingCoupons = true
                dataManager.shouldNavigateToAllCoupons = false
            }
        }
        .navigationBarHidden(true)
        .navigationBarBackButtonHidden(true)
    }
    
    // MARK: - 顶部导航
    private var topNavigation: some View {
        HStack {
            // Logo
            Image(systemName: "person.circle.fill")
                .font(AppTheme.Typography.title2)
                .foregroundColor(AppTheme.Colors.accent)
            
            Text(dataManager.currentLanguage == "zh" ? AppStrings.Me.membershipCenter : AppStrings.Me.membershipCenterEn)
                .font(.system(size: 21, weight: .bold))
                .foregroundColor(AppTheme.Colors.primaryText)
            
            Spacer()
            
            // 徽章详情按钮（从卡片移动到这里）
            if dataManager.currentUser != nil {
                Button(action: {
                    showingUnifiedProfile = true
                }) {
                    Image(systemName: "ellipsis")
                        .font(.system(size: 16, weight: .semibold))
                        .foregroundColor(AppTheme.Colors.primaryText)
                        .frame(width: 30, height: 15)
                        .background(AppTheme.Colors.accent)
                        .cornerRadius(8)
                }
                .offset(x: 2)
            }
            
            // 语言切换
            Button(action: {
                dataManager.switchLanguage()
            }) {
                Image(systemName: "globe")
                    .font(.title3)
                    .foregroundColor(AppTheme.Colors.background)
                    .frame(width: 22, height: 22)
                    .background(
                        Circle()
                            .fill(AppTheme.Colors.accent)
                    )
            }
            .offset(x: 2)
            
            // 设置按钮
            if dataManager.currentUser != nil {
                Button(action: { showingSettings = true }) {
                    Image(systemName: "gearshape.fill")
                        .font(AppTheme.Typography.title3)
                        .foregroundColor(AppTheme.Colors.primaryText)
                        .frame(width: 35, height: 35)
                }
            }
        }
        .padding(.horizontal, 20)
        .padding(.top, 10)
        .padding(.bottom, 15)
    }
    
    // MARK: - 会员等级展示组件
    private func memberInfoCard(user: User) -> some View {
        return VStack(spacing: 20) {
            VStack(spacing: 20) {
            // 四个等级角色展示
                HStack(spacing: 0) {
                    // Neon Rookie (蓝调萌牛)
                    VStack(spacing: 8) {
                        ZStack {
                            // 聚光灯效果（仅当前等级显示）
                            if user.membershipLevel == .lv1 {
                                // 聚光灯台子效果
                                Ellipse()
                                    .fill(
                                        RadialGradient(
                                            colors: [
                                                Color.orange.opacity(0.6),
                                                Color.orange.opacity(0.3),
                                                Color.clear
                                            ],
                                            center: .center,
                                            startRadius: 8,
                                            endRadius: 60
                                        )
                                    )
                                    .frame(width: 120, height: 30)
                                    .offset(y: 50)
                                    .blur(radius: 3)
                            }
                            
                            Image("L1NeonRookie")
                                .resizable()
                                .aspectRatio(contentMode: .fit)
                                .frame(width: 82, height: 82)
                                .scaleEffect(user.membershipLevel == .lv1 ? 1.1 : 1.0)
                        }
                        .padding(.top, 10)
                        
                        Text(dataManager.currentLanguage == "zh" ? "蓝调\n萌牛" : "Neon\nRookie")
                            .font(.system(size: 10, weight: .semibold))
                            .foregroundColor(.white)
                            .multilineTextAlignment(.center)
                            .lineLimit(2)
                    }
                    .frame(maxWidth: .infinity)
                    
                    // Hype Blaze (橙燃玩家)
                    VStack(spacing: 8) {
                        ZStack {
                            // 聚光灯效果（仅当前等级显示）
                            if user.membershipLevel == .lv2 {
                                // 聚光灯台子效果
                                Ellipse()
                                    .fill(
                                        RadialGradient(
                                            colors: [
                                                Color.orange.opacity(0.6),
                                                Color.orange.opacity(0.3),
                                                Color.clear
                                            ],
                                            center: .center,
                                            startRadius: 8,
                                            endRadius: 60
                                        )
                                    )
                                    .frame(width: 120, height: 30)
                                    .offset(y: 50)
                                    .blur(radius: 3)
                            }
                            
                            Image("L2HypeBlaze")
                                .resizable()
                                .aspectRatio(contentMode: .fit)
                                .frame(width: 82, height: 82)
                                .scaleEffect(user.membershipLevel == .lv2 ? 1.1 : 1.0)
                        }
                        .padding(.top, 10)
                        
                        Text(dataManager.currentLanguage == "zh" ? "橙燃\n玩家" : "Hype\nBlaze")
                            .font(.system(size: 10, weight: .semibold))
                            .foregroundColor(.white)
                            .multilineTextAlignment(.center)
                            .lineLimit(2)
                    }
                    .frame(maxWidth: .infinity)
                    
                    // Vibe Regent (紫域主理人)
                    VStack(spacing: 8) {
                        ZStack {
                            // 聚光灯效果（仅当前等级显示）
                            if user.membershipLevel == .lv3 {
                                // 聚光灯台子效果
                                Ellipse()
                                    .fill(
                                        RadialGradient(
                                            colors: [
                                                Color.orange.opacity(0.6),
                                                Color.orange.opacity(0.3),
                                                Color.clear
                                            ],
                                            center: .center,
                                            startRadius: 8,
                                            endRadius: 60
                                        )
                                    )
                                    .frame(width: 120, height: 30)
                                    .offset(y: 50)
                                    .blur(radius: 3)
                            }
                            
                            Image("L3VibeRegent")
                                .resizable()
                                .aspectRatio(contentMode: .fit)
                                .frame(width: 82, height: 82)
                                .scaleEffect(user.membershipLevel == .lv3 ? 1.1 : 1.0)
                        }
                        .padding(.top, 10)
                        
                        Text(dataManager.currentLanguage == "zh" ? "紫域\n主理人" : "Vibe\nRegent")
                            .font(.system(size: 10, weight: .semibold))
                            .foregroundColor(.white)
                            .multilineTextAlignment(.center)
                            .lineLimit(2)
                    }
                    .frame(maxWidth: .infinity)
                    
                    // Aureus Legend (金耀传说)
                    VStack(spacing: 8) {
                        ZStack {
                            // 聚光灯效果（仅当前等级显示）
                            if user.membershipLevel == .lv4 {
                                // 聚光灯台子效果
                                Ellipse()
                                    .fill(
                                        RadialGradient(
                                            colors: [
                                                Color.orange.opacity(0.6),
                                                Color.orange.opacity(0.3),
                                                Color.clear
                                            ],
                                            center: .center,
                                            startRadius: 8,
                                            endRadius: 60
                                        )
                                    )
                                    .frame(width: 120, height: 30)
                                    .offset(y: 50)
                                    .blur(radius: 3)
                            }
                            
                            Image("L4AureusLegend")
                                .resizable()
                                .aspectRatio(contentMode: .fit)
                                .frame(width: 82, height: 82)
                                .scaleEffect(user.membershipLevel == .lv4 ? 1.1 : 1.0)
                        }
                        .padding(.top, 10)
                        
                        Text(dataManager.currentLanguage == "zh" ? "金耀\n传说" : "Aureus\nLegend")
                            .font(.system(size: 10, weight: .semibold))
                            .foregroundColor(.white)
                            .multilineTextAlignment(.center)
                            .lineLimit(2)
                    }
                    .frame(maxWidth: .infinity)
                }
                .padding(.horizontal, 10)
                .padding(.bottom, 3)
                
                // 等级进度条和点数显示
                VStack(spacing: 6) {
                    // 分段式进度条
                    GeometryReader { geometry in
                        let segmentWidth = (geometry.size.width - 6) / 4  // 减去3个分隔符的宽度(3*2=6)
                        HStack(spacing: 0) {
                            // 第一段：0-200 pts
                            ZStack(alignment: .leading) {
                                Rectangle()
                                    .fill(Color.gray.opacity(0.3))
                                    .frame(height: 8)
                                    .cornerRadius(4)
                                
                                if user.totalPointsEarned > 0 {
                                    Rectangle()
                                        .fill(
                                            LinearGradient(
                                                colors: [Color.orange, Color.orange.opacity(0.8)],
                                                startPoint: .leading,
                                                endPoint: .trailing
                                            )
                                        )
                                        .frame(width: min(CGFloat(user.totalPointsEarned) / 200.0, 1.0) * segmentWidth, height: 8)
                                        .cornerRadius(4)
                                }
                            }
                            .frame(width: segmentWidth)
                            
                            // 第一个竖杠分隔符
                            Rectangle()
                                .fill(Color.white)
                                .frame(width: 2, height: 16)
                            
                            // 第二段：201-800 pts
                            ZStack(alignment: .leading) {
                                Rectangle()
                                    .fill(Color.gray.opacity(0.3))
                                    .frame(height: 8)
                                    .cornerRadius(4)
                                
                                if user.totalPointsEarned > 200 {
                                    Rectangle()
                                        .fill(
                                            LinearGradient(
                                                colors: [Color.orange, Color.orange.opacity(0.8)],
                                                startPoint: .leading,
                                                endPoint: .trailing
                                            )
                                        )
                                        .frame(width: min(CGFloat(user.totalPointsEarned - 200) / 600.0, 1.0) * segmentWidth, height: 8)
                                        .cornerRadius(4)
                                }
                            }
                            .frame(width: segmentWidth)
                            
                            // 第二个竖杠分隔符
                            Rectangle()
                                .fill(Color.white)
                                .frame(width: 2, height: 16)
                            
                            // 第三段：801-1600 pts
                            ZStack(alignment: .leading) {
                                Rectangle()
                                    .fill(Color.gray.opacity(0.3))
                                    .frame(height: 8)
                                    .cornerRadius(4)
                                
                                if user.totalPointsEarned > 800 {
                                    Rectangle()
                                        .fill(
                                            LinearGradient(
                                                colors: [Color.orange, Color.orange.opacity(0.8)],
                                                startPoint: .leading,
                                                endPoint: .trailing
                                            )
                                        )
                                        .frame(width: min(CGFloat(user.totalPointsEarned - 800) / 800.0, 1.0) * segmentWidth, height: 8)
                                        .cornerRadius(4)
                                }
                            }
                            .frame(width: segmentWidth)
                            
                            // 第三个竖杠分隔符
                            Rectangle()
                                .fill(Color.white)
                                .frame(width: 2, height: 16)
                            
                            // 第四段：1601+ pts
                            ZStack(alignment: .leading) {
                                Rectangle()
                                    .fill(Color.gray.opacity(0.3))
                                    .frame(height: 8)
                                    .cornerRadius(4)
                                
                                if user.totalPointsEarned > 1600 {
                                    Rectangle()
                                        .fill(
                                            LinearGradient(
                                                colors: [Color.orange, Color.orange.opacity(0.8)],
                                                startPoint: .leading,
                                                endPoint: .trailing
                                            )
                                        )
                                        .frame(height: 8)
                                        .cornerRadius(4)
                                }
                            }
                            .frame(width: segmentWidth)
                        }
                    }
                    .frame(height: 16)
                    
                    // 点数门槛显示
                    HStack {
                        Spacer()
                        Spacer()
                        
                        Text("200 Pts")
                            .font(.system(size: 9, weight: .medium))
                            .foregroundColor(.white.opacity(0.7))
                        
                        Spacer()
                        Spacer()
                        
                        Text("800 Pts")
                            .font(.system(size: 9, weight: .medium))
                            .foregroundColor(.white.opacity(0.7))
                        
                        Spacer()
                        Spacer()
                        
                        Text("1600 Pts")
                            .font(.system(size: 9, weight: .medium))
                            .foregroundColor(.white.opacity(0.7))
                        
                        Spacer()
                    }
                }
                .padding(.top, 5)
            }
            .padding(.vertical, 12)
            .background(
                RoundedRectangle(cornerRadius: 20)
                    .fill(
                        LinearGradient(
                            colors: [
                                Color(red: 0.35, green: 0.32, blue: 0.30),
                                Color(red: 0.25, green: 0.22, blue: 0.20),
                                Color(red: 0.15, green: 0.12, blue: 0.10)
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .overlay(
                        RoundedRectangle(cornerRadius: 20)
                            .stroke(
                                LinearGradient(
                                    colors: [
                                        Color.white.opacity(0.2),
                                        Color.clear
                                    ],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                ),
                                lineWidth: 1
                            )
                    )
                    .shadow(color: Color.black.opacity(0.3), radius: 10, x: 0, y: 5)
            )

            

        }
        .frame(maxWidth: .infinity)
    }
    
    // MARK: - 积分概览
    private func pointsOverview(user: User) -> some View {
        VStack(spacing: 15) {
            HStack {
                Text(dataManager.currentLanguage == "zh" ? "积分概览" : "Points Overview")
                    .font(.headline)
                    .fontWeight(.bold)
                    .foregroundColor(.white)
                
                Spacer()
            }
            
            VStack(spacing: 15) {
                // 第一行：当前积分和历史累计积分
                HStack(spacing: 15) {
                    // 当前积分
                    VStack(spacing: 8) {
                        Text("\(user.points)")
                            .font(.title)
                            .fontWeight(.bold)
                            .foregroundColor(Color(red: 1.0, green: 0.84, blue: 0.0))
                        
                        Text(dataManager.currentLanguage == "zh" ? AppStrings.Me.availablePoints : AppStrings.Me.availablePointsEn)
                            .font(AppTheme.Typography.caption)
                            .foregroundColor(AppTheme.Colors.secondaryText)
                    }
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, 20)
                    .background(
                        RoundedRectangle(cornerRadius: 12)
                            .fill(
                                LinearGradient(
                                    colors: [
                                        Color(red: 0.35, green: 0.30, blue: 0.25),
                                        Color(red: 0.25, green: 0.20, blue: 0.15),
                                        Color(red: 0.15, green: 0.10, blue: 0.05)
                                    ],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                            )
                            .overlay(
                                RoundedRectangle(cornerRadius: 12)
                                    .stroke(
                                        LinearGradient(
                                            colors: [
                                                Color(red: 1.0, green: 0.84, blue: 0.0).opacity(0.3),
                                                Color.clear
                                            ],
                                            startPoint: .topLeading,
                                            endPoint: .bottomTrailing
                                        ),
                                        lineWidth: 1
                                    )
                            )
                            .shadow(color: Color(red: 1.0, green: 0.84, blue: 0.0).opacity(0.2), radius: 6, x: 0, y: 3)
                    )
                    
                    // 历史累计积分
                    VStack(spacing: 8) {
                        Text("\(user.totalPointsEarned)")
                            .font(.title)
                            .fontWeight(.bold)
                            .foregroundColor(Color(red: 0.8, green: 0.4, blue: 1.0))
                        
                        Text(dataManager.currentLanguage == "zh" ? AppStrings.Me.totalEarned : AppStrings.Me.totalEarnedEn)
                            .font(AppTheme.Typography.caption)
                            .foregroundColor(AppTheme.Colors.secondaryText)
                    }
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, 20)
                    .background(
                        RoundedRectangle(cornerRadius: 12)
                            .fill(
                                LinearGradient(
                                    colors: [
                                        Color(red: 0.30, green: 0.25, blue: 0.35),
                                        Color(red: 0.20, green: 0.15, blue: 0.25),
                                        Color(red: 0.10, green: 0.05, blue: 0.15)
                                    ],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                            )
                            .overlay(
                                RoundedRectangle(cornerRadius: 12)
                                    .stroke(
                                        LinearGradient(
                                            colors: [
                                                Color(red: 0.8, green: 0.4, blue: 1.0).opacity(0.3),
                                                Color.clear
                                            ],
                                            startPoint: .topLeading,
                                            endPoint: .bottomTrailing
                                        ),
                                        lineWidth: 1
                                    )
                            )
                            .shadow(color: Color(red: 0.8, green: 0.4, blue: 1.0).opacity(0.2), radius: 6, x: 0, y: 3)
                    )
                }
                

            }
        }
    }
    
    // MARK: - 社交媒体Logo
    private var socialMediaLogos: some View {
        HStack(spacing: 32) {
            ForEach(SocialMediaManager.homePagePlatforms, id: \.self) { platform in
                Button(action: {
                    SocialMediaManager.openSocialMedia(platform: platform)
                }) {
                    Image(platform.iconName)
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 38.4, height: 38.4) // 48 * 0.8 = 38.4
                }
                .buttonStyle(PlainButtonStyle())
            }
        }
        .padding(.horizontal, 20)
        .padding(.vertical, 16)
    }
    
    // MARK: - 社交互动卡片
    private func socialInteractionCard(user: User) -> some View {
        Button(action: {
            showingSocialMediaDetail = true
        }) {
            VStack(spacing: 12) {
                // 标题区域
                HStack {
                    VStack(alignment: .leading, spacing: 4) {
                        Text(dataManager.currentLanguage == "zh" ? "社交互动中心" : "Social Media Center")
                            .font(.system(size: 20, weight: .bold, design: .rounded))
                            .foregroundStyle(
                                LinearGradient(
                                    colors: [Color(red: 0.0, green: 0.8, blue: 1.0), Color(red: 0.4, green: 0.6, blue: 1.0)],
                                    startPoint: .leading,
                                    endPoint: .trailing
                                )
                            )
                        
                        Text(dataManager.currentLanguage == "zh" ? "提交互动，赚取积分" : "Submit Interactions and Earn Points")
                            .font(.system(size: 13, weight: .medium))
                            .foregroundColor(.white.opacity(0.8))
                    }
                    
                    Spacer()
                    
                    // 进入箭头和装饰图标
                    HStack(spacing: 12) {
                        ZStack {
                            Circle()
                                .fill(
                                    RadialGradient(
                                        colors: [Color(red: 0.0, green: 0.8, blue: 1.0).opacity(0.3), Color.clear],
                                        center: .center,
                                        startRadius: 0,
                                        endRadius: 25
                                    )
                                )
                                .frame(width: 50, height: 50)
                            
                            Image(systemName: "network")
                                .font(.system(size: 22, weight: .medium))
                                .foregroundColor(Color(red: 0.0, green: 0.8, blue: 1.0))
                        }
                        
                        Image(systemName: "chevron.right")
                            .font(.system(size: 16, weight: .semibold))
                            .foregroundColor(Color(red: 0.0, green: 0.8, blue: 1.0))
                    }
                }
            }
            .padding(16)
        }
        .background(
            ZStack {
                // 主背景
                RoundedRectangle(cornerRadius: 20)
                    .fill(
                        LinearGradient(
                            colors: [
                                Color(red: 0.05, green: 0.05, blue: 0.15),
                                Color(red: 0.1, green: 0.1, blue: 0.25),
                                Color(red: 0.05, green: 0.05, blue: 0.20)
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                
                // 科技感边框
                RoundedRectangle(cornerRadius: 20)
                    .stroke(
                        LinearGradient(
                            colors: [
                                Color(red: 0.0, green: 0.8, blue: 1.0).opacity(0.6),
                                Color(red: 0.4, green: 0.6, blue: 1.0).opacity(0.3),
                                Color.clear
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        ),
                        lineWidth: 1.5
                    )
                
                // 光效装饰
                RoundedRectangle(cornerRadius: 20)
                    .fill(
                        RadialGradient(
                            colors: [Color(red: 0.0, green: 0.8, blue: 1.0).opacity(0.1), Color.clear],
                            center: .topLeading,
                            startRadius: 0,
                            endRadius: 150
                        )
                    )
            }
        )
        .shadow(color: Color(red: 0.0, green: 0.8, blue: 1.0).opacity(0.3), radius: 15, x: 0, y: 8)
        .shadow(color: Color.black.opacity(0.4), radius: 20, x: 0, y: 10)
    }
    
    // MARK: - 社交平台按钮
    private func socialPlatformButton(platform: String, icon: String, color: Color, user: User) -> some View {
        Button(action: {
            // 社交媒体提交逻辑
            submitSocialMediaEvidence(platform: platform, user: user)
        }) {
            VStack(spacing: 8) {
                ZStack {
                    // 背景圆圈
                    Circle()
                        .fill(
                            LinearGradient(
                                colors: [color.opacity(0.8), color.opacity(0.6)],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .frame(width: 45, height: 45)
                    
                    // 光效
                    Circle()
                        .fill(
                            RadialGradient(
                                colors: [Color.white.opacity(0.3), Color.clear],
                                center: .topLeading,
                                startRadius: 0,
                                endRadius: 22
                            )
                        )
                        .frame(width: 45, height: 45)
                    
                    // 图标
                    Image(systemName: icon)
                        .font(.system(size: 20, weight: .semibold))
                        .foregroundColor(.white)
                }
                
                // 平台名称
                Text(platform)
                    .font(.system(size: 11, weight: .bold, design: .rounded))
                    .foregroundColor(.white)
                    .lineLimit(1)
                    .minimumScaleFactor(0.8)
            }
        }
        .buttonStyle(PlainButtonStyle())
        .scaleEffect(1.0)
        .animation(.spring(response: 0.3, dampingFraction: 0.7), value: platform)
    }
    
    private func submitSocialMediaEvidence(platform: String, user: User) {
        // 将字符串平台转换为SocialPlatform枚举
        guard let socialPlatform = convertStringToPlatform(platform) else {
            showSubmissionAlert(message: language == "zh" ? "无效的平台选择" : "Invalid platform selection")
            return
        }
        
        // 检查用户是否可以提交
        let canSubmitResult = socialMediaManager.canSubmit(userId: user.id.uuidString)
        if !canSubmitResult.success {
            showSubmissionAlert(message: canSubmitResult.message)
            return
        }
        
        selectedPlatform = socialPlatform
        submissionDescription = ""
        submissionLink = ""
        selectedImage = nil
        submissionType = .link
        showingSubmissionSheet = true
    }
    
    private func convertStringToPlatform(_ platform: String) -> SocialPlatform? {
        switch platform {
        case "TikTok": return .tiktok
        case "微博": return .weibo
        case "Facebook": return .facebook
        case "Instagram": return .instagram
        case "小红书": return .xiaohongshu
        case "微信": return .wechat
        case "抖音": return .douyin
        case "Twitter": return .twitter
        default: return nil
        }
    }
    
    private func handleImageSelection(image: UIImage) {
        selectedImage = image
    }
    
    private func submitEvidence() {
        guard let platform = selectedPlatform,
              let user = dataManager.currentUser else { return }
        
        let description = submissionDescription.isEmpty ? 
            (language == "zh" ? "社交媒体互动证据" : "Social media interaction evidence") : 
            submissionDescription
        
        var evidenceURL = ""
        
        if submissionType == .link {
            if submissionLink.isEmpty {
                showSubmissionAlert(message: language == "zh" ? "请输入链接" : "Please enter a link")
                return
            }
            evidenceURL = submissionLink
        } else {
            if selectedImage == nil {
                showSubmissionAlert(message: language == "zh" ? "请选择图片" : "Please select an image")
                return
            }
            // 这里应该上传图片并获取URL，暂时使用占位符
            evidenceURL = "image_placeholder_\(Date().timeIntervalSince1970)"
        }
        
        let result = socialMediaManager.submitEvidence(
            userId: user.id.uuidString,
            platform: platform.rawValue,
            interactionType: .like,
            description: description,
            link: submissionType == .link ? evidenceURL : nil,
            imageData: submissionType == .image ? selectedImage?.jpegData(compressionQuality: 0.8) : nil,
            language: language
        )
        
        if result.success {
            showSubmissionAlert(message: result.message)
            showingSubmissionSheet = false
        } else {
            showSubmissionAlert(message: result.message)
        }
        
        // 重置状态
        selectedPlatform = nil
        submissionDescription = ""
        submissionLink = ""
        selectedImage = nil
    }
    
    private func showSubmissionAlert(message: String) {
        submissionAlertMessage = message
        showingSubmissionAlert = true
    }
    
    // MARK: - 社交媒体提交表单界面
    private var socialMediaSubmissionSheet: some View {
        NavigationView {
            ZStack {
                // 背景渐变
                LinearGradient(
                    colors: [
                        Color(red: 0.05, green: 0.05, blue: 0.1),
                        Color(red: 0.1, green: 0.1, blue: 0.15),
                        Color(red: 0.08, green: 0.08, blue: 0.12)
                    ],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .ignoresSafeArea()
                
                ScrollView {
                    VStack(spacing: 24) {
                        // 标题区域
                        VStack(spacing: 8) {
                            Text(language == "zh" ? "提交社交媒体互动" : "Submit Social Media Interaction")
                                .font(.title2)
                                .fontWeight(.bold)
                                .foregroundColor(.white)
                            
                            if let platform = selectedPlatform {
                                Text("\(language == "zh" ? "平台：" : "Platform: ")\(platform.rawValue)")
                                    .font(.subheadline)
                                    .foregroundColor(.white.opacity(0.8))
                            }
                        }
                        .padding(.top, 20)
                        
                        // 提交类型选择
                        VStack(alignment: .leading, spacing: 12) {
                            Text(language == "zh" ? "提交方式" : "Submission Type")
                                .font(.headline)
                                .foregroundColor(.white)
                            
                            HStack(spacing: 16) {
                                // 链接提交
                                Button(action: {
                                    submissionType = .link
                                }) {
                                    HStack {
                                        Image(systemName: submissionType == .link ? "checkmark.circle.fill" : "circle")
                                            .foregroundColor(submissionType == .link ? Color(red: 0.0, green: 0.8, blue: 1.0) : .white.opacity(0.6))
                                        Text(language == "zh" ? "链接" : "Link")
                                            .foregroundColor(.white)
                                    }
                                    .padding(.vertical, 8)
                                    .padding(.horizontal, 16)
                                    .background(
                                        RoundedRectangle(cornerRadius: 12)
                                            .fill(submissionType == .link ? Color(red: 0.0, green: 0.8, blue: 1.0).opacity(0.2) : Color.white.opacity(0.1))
                                    )
                                }
                                
                                // 图片提交
                                Button(action: {
                                    submissionType = .image
                                }) {
                                    HStack {
                                        Image(systemName: submissionType == .image ? "checkmark.circle.fill" : "circle")
                                            .foregroundColor(submissionType == .image ? Color(red: 0.0, green: 0.8, blue: 1.0) : .white.opacity(0.6))
                                        Text(language == "zh" ? "图片" : "Image")
                                            .foregroundColor(.white)
                                    }
                                    .padding(.vertical, 8)
                                    .padding(.horizontal, 16)
                                    .background(
                                        RoundedRectangle(cornerRadius: 12)
                                            .fill(submissionType == .image ? Color(red: 0.0, green: 0.8, blue: 1.0).opacity(0.2) : Color.white.opacity(0.1))
                                    )
                                }
                                
                                Spacer()
                            }
                        }
                        .padding(.horizontal, 20)
                        
                        // 提交内容区域
                        VStack(spacing: 20) {
                            if submissionType == .link {
                                // 链接输入
                                VStack(alignment: .leading, spacing: 8) {
                                    Text(language == "zh" ? "互动链接" : "Interaction Link")
                                        .font(.headline)
                                        .foregroundColor(.white)
                                    
                                    TextField(
                                        language == "zh" ? "请输入社交媒体互动链接" : "Enter social media interaction link",
                                        text: $submissionLink
                                    )
                                    .textFieldStyle(PlainTextFieldStyle())
                                    .padding()
                                    .background(
                                        RoundedRectangle(cornerRadius: 12)
                                            .fill(Color.white.opacity(0.1))
                                    )
                                    .foregroundColor(.white)
                                    .autocapitalization(.none)
                                    .disableAutocorrection(true)
                                }
                            } else {
                                // 图片选择
                                VStack(alignment: .leading, spacing: 8) {
                                    Text(language == "zh" ? "互动截图" : "Interaction Screenshot")
                                        .font(.headline)
                                        .foregroundColor(.white)
                                    
                                    Button(action: {
                                        showingImagePicker = true
                                    }) {
                                        if let image = selectedImage {
                                            Image(uiImage: image)
                                                .resizable()
                                                .aspectRatio(contentMode: .fit)
                                                .frame(maxHeight: 200)
                                                .cornerRadius(12)
                                        } else {
                                            VStack(spacing: 12) {
                                                Image(systemName: "photo.badge.plus")
                                                    .font(.system(size: 40))
                                                    .foregroundColor(.white.opacity(0.6))
                                                
                                                Text(language == "zh" ? "点击选择图片" : "Tap to select image")
                                                    .foregroundColor(.white.opacity(0.8))
                                            }
                                            .frame(height: 120)
                                            .frame(maxWidth: .infinity)
                                            .background(
                                                RoundedRectangle(cornerRadius: 12)
                                                    .fill(Color.white.opacity(0.1))
                                                    .overlay(
                                                        RoundedRectangle(cornerRadius: 12)
                                                            .stroke(Color.white.opacity(0.3), style: StrokeStyle(lineWidth: 2, dash: [8]))
                                                    )
                                            )
                                        }
                                    }
                                }
                            }
                            
                            // 描述输入
                            VStack(alignment: .leading, spacing: 8) {
                                Text(language == "zh" ? "描述（可选）" : "Description (Optional)")
                                    .font(.headline)
                                    .foregroundColor(.white)
                                
                                TextField(
                                    language == "zh" ? "请描述您的互动内容..." : "Describe your interaction...",
                                    text: $submissionDescription,
                                    axis: .vertical
                                )
                                .textFieldStyle(PlainTextFieldStyle())
                                .padding()
                                .background(
                                    RoundedRectangle(cornerRadius: 12)
                                        .fill(Color.white.opacity(0.1))
                                )
                                .foregroundColor(.white)
                                .frame(minHeight: 80)
                            }
                        }
                        .padding(.horizontal, 20)
                        
                        // 提交按钮
                        Button(action: {
                            submitEvidence()
                        }) {
                            Text(language == "zh" ? "提交审核" : "Submit for Review")
                                .font(.headline)
                                .fontWeight(.semibold)
                                .foregroundColor(.white)
                                .frame(maxWidth: .infinity)
                                .padding()
                                .background(
                                    LinearGradient(
                                        colors: [Color(red: 0.0, green: 0.8, blue: 1.0), Color(red: 0.4, green: 0.6, blue: 1.0)],
                                        startPoint: .leading,
                                        endPoint: .trailing
                                    )
                                )
                                .cornerRadius(12)
                        }
                        .padding(.horizontal, 20)
                        .padding(.bottom, 30)
                    }
                }
            }
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button(language == "zh" ? "取消" : "Cancel") {
                        showingSubmissionSheet = false
                    }
                    .foregroundColor(Color(red: 0.0, green: 0.8, blue: 1.0))
                }
            }
        }
    }
    
    // MARK: - 互动记录卡片
    private func interactionRecordsCard(user: User) -> some View {
        let userSubmissions = socialMediaManager.getUserSubmissions(userId: user.id.uuidString)
                        let pointsStats = socialMediaManager.getUserPointsStats(userId: user.id.uuidString)
        let monthlyPoints = pointsStats.monthly
        let dailyPoints = pointsStats.daily
        
        return VStack(spacing: 20) {
            // 标题区域
            HStack {
                VStack(alignment: .leading, spacing: 4) {
                    Text(dataManager.currentLanguage == "zh" ? "互动审核记录" : "Interaction Records")
                        .font(.system(size: 20, weight: .bold, design: .rounded))
                        .foregroundStyle(
                            LinearGradient(
                                colors: [Color(red: 0.0, green: 0.8, blue: 0.4), Color(red: 0.0, green: 0.6, blue: 0.8)],
                                startPoint: .leading,
                                endPoint: .trailing
                            )
                        )
                    
                    Text(dataManager.currentLanguage == "zh" ? "查看审核状态和积分记录" : "View approval status and points")
                        .font(.system(size: 13, weight: .medium))
                        .foregroundColor(.white.opacity(0.8))
                }
                
                Spacer()
                
                // 科技感装饰图标
                ZStack {
                    Circle()
                        .fill(
                            RadialGradient(
                                colors: [Color(red: 0.0, green: 0.8, blue: 0.4).opacity(0.3), Color.clear],
                                center: .center,
                                startRadius: 0,
                                endRadius: 25
                            )
                        )
                        .frame(width: 50, height: 50)
                    
                    Image(systemName: "checkmark.seal.fill")
                        .font(.system(size: 22, weight: .medium))
                        .foregroundColor(Color(red: 0.0, green: 0.8, blue: 0.4))
                }
            }
            
            if userSubmissions.isEmpty {
                // 空状态
                VStack(spacing: 12) {
                    Image(systemName: "tray")
                        .font(.system(size: 40))
                        .foregroundColor(.white.opacity(0.4))
                    
                    Text(dataManager.currentLanguage == "zh" ? "暂无互动记录" : "No interaction records")
                        .font(.system(size: 16, weight: .medium))
                        .foregroundColor(.white.opacity(0.7))
                    
                    Text(dataManager.currentLanguage == "zh" ? "开始提交社交媒体互动获得积分" : "Start submitting social media interactions to earn points")
                        .font(.system(size: 14))
                        .foregroundColor(.white.opacity(0.5))
                        .multilineTextAlignment(.center)
                }
                .padding(.vertical, 20)
            } else {
                // 审核记录列表
                VStack(spacing: 15) {
                    // 显示最近的记录（最多3条）
                    ForEach(Array(userSubmissions.prefix(3).enumerated()), id: \.offset) { index, submission in
                        interactionRecordItem(
                            platform: submission.platform,
                            date: formatDate(submission.submissionDate),
                            status: submission.status.rawValue,
                            points: submission.pointsAwarded
                        )
                    }
                    
                    // 查看更多按钮（如果有超过3条记录）
                    if userSubmissions.count > 3 {
                        Button(action: {
                            // 查看更多互动记录
                        }) {
                            Text(dataManager.currentLanguage == "zh" ? "查看更多" : "View More")
                                .font(.system(size: 14, weight: .medium))
                                .foregroundColor(Color(red: 0.0, green: 0.8, blue: 0.4))
                                .padding(.vertical, 8)
                                .padding(.horizontal, 16)
                                .background(
                                    RoundedRectangle(cornerRadius: 20)
                                        .stroke(Color(red: 0.0, green: 0.8, blue: 0.4).opacity(0.6), lineWidth: 1)
                                        .background(Color(red: 0.0, green: 0.8, blue: 0.4).opacity(0.1).cornerRadius(20))
                                )
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                }
            }
            
            // 积分统计
            HStack {
                VStack(alignment: .leading, spacing: 4) {
                    Text(dataManager.currentLanguage == "zh" ? "本月已获得" : "This Month")
                        .font(.system(size: 12, weight: .medium))
                        .foregroundColor(.white.opacity(0.7))
                    
                    HStack(alignment: .firstTextBaseline, spacing: 2) {
                        Text("\(monthlyPoints)")
                            .font(.system(size: 20, weight: .bold))
                            .foregroundColor(Color(red: 0.0, green: 0.8, blue: 0.4))
                        
                        Text("/\(SocialMediaConfig.monthlyPointsLimit) " + (dataManager.currentLanguage == "zh" ? "积分" : "Points"))
                            .font(.system(size: 12, weight: .medium))
                            .foregroundColor(.white.opacity(0.7))
                    }
                }
                
                Spacer()
                
                VStack(alignment: .trailing, spacing: 4) {
                    Text(dataManager.currentLanguage == "zh" ? "今日已获得" : "Today")
                        .font(.system(size: 12, weight: .medium))
                        .foregroundColor(.white.opacity(0.7))
                    
                    HStack(alignment: .firstTextBaseline, spacing: 2) {
                        Text("\(dailyPoints)")
                            .font(.system(size: 20, weight: .bold))
                            .foregroundColor(Color(red: 0.0, green: 0.8, blue: 0.4))
                        
                        Text("/\(SocialMediaConfig.dailyPointsLimit) " + (dataManager.currentLanguage == "zh" ? "积分" : "Points"))
                            .font(.system(size: 12, weight: .medium))
                            .foregroundColor(.white.opacity(0.7))
                    }
                }
            }
            .padding(.top, 5)
        }
        .padding(24)
        .background(
            ZStack {
                // 主背景
                RoundedRectangle(cornerRadius: 20)
                    .fill(
                        LinearGradient(
                            colors: [
                                Color(red: 0.05, green: 0.05, blue: 0.15),
                                Color(red: 0.1, green: 0.1, blue: 0.25),
                                Color(red: 0.05, green: 0.05, blue: 0.20)
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                
                // 科技感边框
                RoundedRectangle(cornerRadius: 20)
                    .stroke(
                        LinearGradient(
                            colors: [
                                Color(red: 0.0, green: 0.8, blue: 0.4).opacity(0.6),
                                Color(red: 0.0, green: 0.6, blue: 0.8).opacity(0.3),
                                Color.clear
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        ),
                        lineWidth: 1.5
                    )
                
                // 光效装饰
                RoundedRectangle(cornerRadius: 20)
                    .fill(
                        RadialGradient(
                            colors: [Color(red: 0.0, green: 0.8, blue: 0.4).opacity(0.1), Color.clear],
                            center: .topLeading,
                            startRadius: 0,
                            endRadius: 150
                        )
                    )
            }
        )
        .shadow(color: Color(red: 0.0, green: 0.8, blue: 0.4).opacity(0.3), radius: 15, x: 0, y: 8)
        .shadow(color: Color.black.opacity(0.4), radius: 20, x: 0, y: 10)
    }
    
    // MARK: - 日期格式化辅助函数
    private func formatDate(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter.string(from: date)
    }
    
    // MARK: - 互动记录项
    private func interactionRecordItem(platform: String, date: String, status: String, points: Int) -> some View {
        HStack(spacing: 12) {
            // 平台图标
            ZStack {
                Circle()
                    .fill(Color(red: 0.1, green: 0.1, blue: 0.2))
                    .frame(width: 36, height: 36)
                
                Image(systemName: getPlatformIcon(platform))
                    .font(.system(size: 16))
                    .foregroundColor(getPlatformColor(platform))
            }
            
            // 记录信息
            VStack(alignment: .leading, spacing: 2) {
                Text(platform)
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(.white)
                
                Text(date)
                    .font(.system(size: 12))
                    .foregroundColor(.white.opacity(0.6))
            }
            
            Spacer()
            
            // 状态标签
            HStack(spacing: 4) {
                Circle()
                    .fill(getStatusColor(status))
                    .frame(width: 8, height: 8)
                
                Text(getStatusText(status))
                    .font(.system(size: 12, weight: .medium))
                    .foregroundColor(getStatusColor(status))
            }
            
            // 积分
            if status == "approved" {
                Text("+\(points)")
                    .font(.system(size: 16, weight: .bold))
                    .foregroundColor(Color(red: 0.0, green: 0.8, blue: 0.4))
            } else {
                Text("+\(points)")
                    .font(.system(size: 16, weight: .bold))
                    .foregroundColor(Color.gray.opacity(0.6))
            }
        }
        .padding(.vertical, 10)
        .padding(.horizontal, 12)
        .background(
            RoundedRectangle(cornerRadius: 12)
                .fill(Color(red: 0.1, green: 0.1, blue: 0.2).opacity(0.5))
        )
    }
    
    // MARK: - 辅助函数
    private func getPlatformIcon(_ platform: String) -> String {
        switch platform {
        case "TikTok": return "music.note"
        case "Google": return "star.fill"
        case "Facebook": return "f.circle.fill"
        case "Instagram": return "camera.fill"
        case "小红书": return "book.fill"
        default: return "network"
        }
    }
    
    private func getPlatformColor(_ platform: String) -> Color {
        switch platform {
        case "TikTok": return Color.white
        case "Google": return Color(red: 0.26, green: 0.52, blue: 0.96)
        case "Facebook": return Color(red: 0.24, green: 0.35, blue: 0.60)
        case "Instagram": return Color(red: 0.83, green: 0.32, blue: 0.55)
        case "小红书": return Color(red: 0.93, green: 0.26, blue: 0.26)
        default: return Color(red: 0.5, green: 0.5, blue: 0.5)
        }
    }
    
    private func getStatusColor(_ status: String) -> Color {
        switch status {
        case "approved": return Color(red: 0.0, green: 0.8, blue: 0.4)
        case "pending": return Color(red: 0.9, green: 0.7, blue: 0.0)
        case "rejected": return Color(red: 0.9, green: 0.2, blue: 0.2)
        default: return Color.gray
        }
    }
    
    private func getStatusText(_ status: String) -> String {
        switch status {
        case "approved": return dataManager.currentLanguage == "zh" ? "已通过" : "Approved"
        case "pending": return dataManager.currentLanguage == "zh" ? "审核中" : "Pending"
        case "rejected": return dataManager.currentLanguage == "zh" ? "已拒绝" : "Rejected"
        default: return ""
        }
    }
    
    // MARK: - 我的优惠券卡片（独立一行）
    private var myCouponsCard: some View {
        VStack(spacing: 10) {
            Text(dataManager.currentLanguage == "zh" ? AppStrings.Me.memberServices : AppStrings.Me.memberServicesEn)
                .font(AppTheme.Typography.headline)
                .fontWeight(.semibold)
                .foregroundColor(AppTheme.Colors.primaryText)
                .frame(maxWidth: .infinity, alignment: .leading)
            
            // 我的优惠券 - 全宽卡片
            Button(action: { showingCoupons = true }) {
                HStack(spacing: 15) {
                    // 图标
                    Image(systemName: "ticket.fill")
                        .font(.title2)
                        .foregroundColor(.white)
                    
                    // 文字内容
                    VStack(alignment: .leading, spacing: 4) {
                        Text(dataManager.currentLanguage == "zh" ? AppStrings.Me.myCoupons : AppStrings.Me.myCouponsEn)
                            .font(AppTheme.Typography.subheadline)
                            .fontWeight(.medium)
                            .foregroundColor(AppTheme.Colors.primaryText)
                        
                        Text(dataManager.currentLanguage == "zh" ? "\(dataManager.getAvailableCouponsCount()) \(AppStrings.Me.available)" : "\(dataManager.getAvailableCouponsCount()) \(AppStrings.Me.availableEn)")
                            .font(AppTheme.Typography.caption)
                            .foregroundColor(AppTheme.Colors.accentSecondary)
                    }
                    
                    Spacer()
                    
                    // 箭头
                    Image(systemName: "chevron.right")
                        .font(.caption)
                        .foregroundColor(.white.opacity(0.6))
                }
                .frame(maxWidth: .infinity)
                .padding(.vertical, 20)
                .padding(.horizontal, 20)
                .background(
                    ZStack {
                        // 主背景
                        RoundedRectangle(cornerRadius: 15)
                            .fill(
                                LinearGradient(
                                    colors: [
                                        Color(red: 0.35, green: 0.35, blue: 0.4),
                                        Color(red: 0.25, green: 0.25, blue: 0.3),
                                        Color(red: 0.2, green: 0.2, blue: 0.25)
                                    ],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                            )
                        
                        // 内部高光
                        RoundedRectangle(cornerRadius: 15)
                            .fill(
                                LinearGradient(
                                    colors: [
                                        Color.white.opacity(0.1),
                                        Color.clear,
                                        Color.clear
                                    ],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                            )
                    }
                    .overlay(
                        RoundedRectangle(cornerRadius: 15)
                            .stroke(
                                LinearGradient(
                                    colors: [
                                        Color.white.opacity(0.3),
                                        Color.white.opacity(0.1),
                                        Color.clear
                                    ],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                ),
                                lineWidth: 1.5
                            )
                    )
                    .shadow(color: Color.black.opacity(0.4), radius: 12, x: 0, y: 6)
                    .shadow(color: Color.black.opacity(0.2), radius: 4, x: 0, y: 2)
                )
            }
            .buttonStyle(PlainButtonStyle())
        }
    }
    
    // MARK: - 功能菜单
    private var functionsMenu: some View {
        VStack(spacing: 10) {
            // 邀请系统测试按钮
            Button(action: {
                showingInviteTest = true
            }) {
                HStack {
                    Image(systemName: "person.2.fill")
                        .font(.title2)
                        .foregroundColor(.white)
                    
                    VStack(alignment: .leading, spacing: 4) {
                        Text(dataManager.currentLanguage == "zh" ? AppStrings.Me.inviteFriends : AppStrings.Me.inviteFriendsEn)
                            .font(AppTheme.Typography.subheadline)
                            .fontWeight(.medium)
                            .foregroundColor(AppTheme.Colors.primaryText)
                        
                        Text(dataManager.currentLanguage == "zh" ? AppStrings.Me.shareInviteCode : AppStrings.Me.shareInviteCodeEn)
                            .font(AppTheme.Typography.caption)
                            .foregroundColor(AppTheme.Colors.accentSecondary)
                    }
                    
                    Spacer()
                    
                    Image(systemName: "chevron.right")
                        .font(.caption)
                        .foregroundColor(.white.opacity(0.6))
                }
                .frame(maxWidth: .infinity)
                .padding(.vertical, 20)
                .padding(.horizontal, 20)
                .background(
                    ZStack {
                        RoundedRectangle(cornerRadius: 15)
                            .fill(
                                LinearGradient(
                                    colors: [
                                        Color(red: 0.35, green: 0.35, blue: 0.4),
                                        Color(red: 0.25, green: 0.25, blue: 0.3),
                                        Color(red: 0.2, green: 0.2, blue: 0.25)
                                    ],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                            )
                        
                        RoundedRectangle(cornerRadius: 15)
                            .fill(
                                LinearGradient(
                                    colors: [
                                        Color.white.opacity(0.1),
                                        Color.clear,
                                        Color.clear
                                    ],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                            )
                    }
                )
                .overlay(
                    RoundedRectangle(cornerRadius: 15)
                        .stroke(
                            LinearGradient(
                                colors: [
                                    Color.white.opacity(0.3),
                                    Color.white.opacity(0.1),
                                    Color.clear
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            ),
                            lineWidth: 1.5
                        )
                )
                .shadow(color: Color.black.opacity(0.4), radius: 12, x: 0, y: 6)
                .shadow(color: Color.black.opacity(0.2), radius: 4, x: 0, y: 2)
            }
            .buttonStyle(PlainButtonStyle())
        }
    }
    
    // MARK: - 会员制度与积分使用规则
    private var membershipPolicyCard: some View {
        Button(action: {
            showingMembershipPolicy = true
        }) {
            VStack(spacing: 0) {
                // 主要内容区域
                VStack(spacing: 16) {
                    // 标题和图标
                    HStack(spacing: 12) {
                        ZStack {
                            // 发光效果背景
                            Circle()
                                .fill(
                                    RadialGradient(
                                        colors: [
                                            Color(red: 1.0, green: 0.3, blue: 0.8).opacity(0.8),
                                            Color(red: 0.2, green: 0.8, blue: 1.0).opacity(0.6),
                                            Color.clear
                                        ],
                                        center: .center,
                                        startRadius: 5,
                                        endRadius: 25
                                    )
                                )
                                .frame(width: 50, height: 50)
                                .blur(radius: 8)
                            
                            // 主图标
                            Circle()
                                .fill(
                                    LinearGradient(
                                        colors: [
                                            Color(red: 1.0, green: 0.2, blue: 0.8),
                                            Color(red: 0.2, green: 0.6, blue: 1.0),
                                            Color(red: 0.8, green: 0.2, blue: 1.0)
                                        ],
                                        startPoint: .topLeading,
                                        endPoint: .bottomTrailing
                                    )
                                )
                                .frame(width: 44, height: 44)
                                .overlay(
                                    Image(systemName: "doc.text.magnifyingglass")
                                        .font(.system(size: 20, weight: .bold))
                                        .foregroundColor(.white)
                                )
                        }
                        
                        VStack(alignment: .leading, spacing: 4) {
                            Text(dataManager.currentLanguage == "zh" ? AppStrings.Me.membershipGuide : AppStrings.Me.membershipGuideEn)
                                .font(.system(size: 18, weight: .bold, design: .rounded))
                                .foregroundColor(AppTheme.Colors.primaryText)
                                .multilineTextAlignment(.leading)
                            
                            Text(dataManager.currentLanguage == "zh" ? AppStrings.Me.tapToViewRules : AppStrings.Me.tapToViewRulesEn)
                                .font(.system(size: 13, weight: .medium))
                                .foregroundColor(AppTheme.Colors.secondaryText)
                        }
                        
                        Spacer()
                        
                        // 箭头指示器
                        Image(systemName: "chevron.right")
                            .font(.system(size: 16, weight: .bold))
                            .foregroundColor(.white.opacity(0.8))
                    }
                    
                    // 预览内容
                    VStack(alignment: .leading, spacing: 8) {
                        HStack {
                            Image(systemName: "crown.fill")
                                .foregroundColor(Color(red: 1.0, green: 0.8, blue: 0.0))
                                .font(.caption)
                            Text(dataManager.currentLanguage == "zh" ? AppStrings.Me.membershipLevels : AppStrings.Me.membershipLevelsEn)
                                .font(.system(size: 12, weight: .medium))
                                .foregroundColor(AppTheme.Colors.primaryText.opacity(0.9))
                        }
                        
                        HStack {
                            Image(systemName: "target")
                                .foregroundColor(Color(red: 0.3, green: 0.8, blue: 1.0))
                                .font(.caption)
                            Text(dataManager.currentLanguage == "zh" ? AppStrings.Me.pointsTypes : AppStrings.Me.pointsTypesEn)
                                .font(.system(size: 12, weight: .medium))
                                .foregroundColor(AppTheme.Colors.primaryText.opacity(0.9))
                        }
                        
                        HStack {
                            Image(systemName: "ticket.fill")
                                .foregroundColor(Color(red: 1.0, green: 0.4, blue: 0.6))
                                .font(.caption)
                            Text(dataManager.currentLanguage == "zh" ? AppStrings.Me.voucherRules : AppStrings.Me.voucherRulesEn)
                                .font(.system(size: 12, weight: .medium))
                                .foregroundColor(AppTheme.Colors.primaryText.opacity(0.9))
                        }
                    }
                }
                .padding(20)
            }
            .background(
                ZStack {
                    // 主背景
                    RoundedRectangle(cornerRadius: 20)
                        .fill(
                            LinearGradient(
                                colors: [
                                    Color(red: 0.15, green: 0.15, blue: 0.25),
                                    Color(red: 0.08, green: 0.08, blue: 0.18),
                                    Color(red: 0.05, green: 0.05, blue: 0.15)
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                    
                    // 发光边框效果
                    RoundedRectangle(cornerRadius: 20)
                        .stroke(
                            LinearGradient(
                                colors: [
                                    Color(red: 1.0, green: 0.3, blue: 0.8).opacity(0.6),
                                    Color(red: 0.2, green: 0.8, blue: 1.0).opacity(0.4),
                                    Color(red: 0.8, green: 0.2, blue: 1.0).opacity(0.3),
                                    Color.clear
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            ),
                            lineWidth: 2
                        )
                    
                    // 内部高光
                    RoundedRectangle(cornerRadius: 20)
                        .fill(
                            LinearGradient(
                                colors: [
                                    Color.white.opacity(0.1),
                                    Color.clear,
                                    Color.clear
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                }
            )
            .shadow(color: Color(red: 1.0, green: 0.3, blue: 0.8).opacity(0.3), radius: 15, x: 0, y: 8)
            .shadow(color: Color(red: 0.2, green: 0.8, blue: 1.0).opacity(0.2), radius: 8, x: 0, y: 4)
            .shadow(color: Color.black.opacity(0.4), radius: 20, x: 0, y: 10)
        }
        .buttonStyle(PlainButtonStyle())
        .scaleEffect(1.0)
        .animation(.easeInOut(duration: 0.2), value: showingMembershipPolicy)
    }
    
    // MARK: - 会员特权（已移除）
    // private var memberBenefits: some View {
    //     VStack(spacing: 15) {
    //         Text(dataManager.currentLanguage == "zh" ? "会员特权" : "Member Benefits")
    //             .font(.headline)
    //             .fontWeight(.semibold)
    //             .foregroundColor(.white)
    //             .frame(maxWidth: .infinity, alignment: .leading)
    //         
    //         VStack(spacing: 12) {
    //             BenefitRow(
    //                 icon: "gift.fill",
    //                 title: dataManager.currentLanguage == "zh" ? "生日特权" : "Birthday Privilege",
    //                 description: dataManager.currentLanguage == "zh" ? "生日月享受专属优惠" : "Exclusive discounts during birthday month"
    //             )
    //             
    //             BenefitRow(
    //                 icon: "bell.fill",
    //                 title: dataManager.currentLanguage == "zh" ? "优先通知" : "Priority Notification",
    //                 description: dataManager.currentLanguage == "zh" ? "新品上市和活动优先通知" : "Priority notifications for new products and events"
    //             )
    //             
    //             BenefitRow(
    //                 icon: "heart.fill",
    //                 title: dataManager.currentLanguage == "zh" ? "社交奖励" : "Social Rewards",
    //                 description: dataManager.currentLanguage == "zh" ? "分享互动获得额外积分" : "Earn extra points through social interactions"
    //             )
    //         }
    //     }
    // }
    
    // MARK: - 游客视图
    private var guestView: some View {
        VStack(spacing: 30) {
            Spacer()
            
            // 登录提示
            VStack(spacing: 20) {
                Image("Logo")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 80, height: 80)
                
                Text(dataManager.currentLanguage == "zh" ? "登录享受会员特权" : "Login to Enjoy Member Benefits")
                    .font(.title2)
                    .fontWeight(.semibold)
                    .foregroundColor(.white)
                    .multilineTextAlignment(.center)
                
                Text(dataManager.currentLanguage == "zh" ? "积分奖励、专属优惠、社交互动奖励等你来拿" : "Points rewards, exclusive discounts, social interaction rewards await you")
                    .font(.subheadline)
                    .foregroundColor(.gray)
                    .multilineTextAlignment(.center)
                    .padding(.horizontal, 40)
            }
            
            // 登录按钮
            NavigationLink(destination: LoginView().environmentObject(dataManager)) {
                Text(dataManager.currentLanguage == "zh" ? "立即登录" : "Login Now")
                    .font(.headline)
                    .foregroundColor(Color(red: 0.12, green: 0.12, blue: 0.12))
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, 15)
                    .background(
                        RoundedRectangle(cornerRadius: 12)
                            .fill(Color(red: 1.0, green: 0.6, blue: 0.2))
                    )
            }
            .padding(.horizontal, 40)
            
            Spacer()
        }
    }
    
    // MARK: - 会员等级进度
    private func membershipProgress(user: User) -> some View {
        let nextLevel = nextMembershipLevel(current: user.membershipLevel)
        let requiredPoints = requiredPointsForNextLevel(current: user.membershipLevel)
        let progress = min(Double(user.totalPointsEarned) / Double(requiredPoints), 1.0)
        
        return VStack(spacing: 10) {
            HStack {
                Text(dataManager.currentLanguage == "zh" ? "升级进度" : "Upgrade Progress")
                    .font(.subheadline)
                    .fontWeight(.medium)
                    .foregroundColor(.white)
                
                Spacer()
                
                if let next = nextLevel {
                    Text(dataManager.currentLanguage == "zh" ? "距离\(next.rawValue)" : "To \(next.englishName)")
                        .font(.caption)
                        .foregroundColor(.gray)
                }
            }
            
            if nextLevel != nil {
                VStack(spacing: 5) {
                    ProgressView(value: progress)
                        .progressViewStyle(LinearProgressViewStyle(tint: Color(red: 1.0, green: 0.6, blue: 0.2)))
                        .scaleEffect(x: 1, y: 2, anchor: .center)
                    
                    HStack {
                        Text("\(user.totalPointsEarned) 积分")
                            .font(.caption)
                            .foregroundColor(.gray)
                        
                        Spacer()
                        
                        Text("\(requiredPoints) 积分")
                            .font(.caption)
                            .foregroundColor(.gray)
                    }
                }
            } else {
                Text(dataManager.currentLanguage == "zh" ? "已达到最高等级" : "Highest level achieved")
                    .font(.caption)
                    .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
            }
        }
    }
    
    // MARK: - 辅助方法
    private func membershipIcon(for level: MembershipLevel) -> String {
        switch level {
        case .lv1:
            return "person.fill"
        case .lv2:
            return "star.fill"
        case .lv3:
            return "crown.fill"
        case .lv4:
            return "diamond.fill"
        }
    }
    
    private func membershipColor(for level: MembershipLevel) -> Color {
        switch level {
        case .lv1:
            return .gray
        case .lv2:
            return .gray
        case .lv3:
            return Color(red: 1.0, green: 0.8, blue: 0.0)
        case .lv4:
            return Color(red: 0.8, green: 0.8, blue: 1.0)
        }
    }
    
    private func membershipDisplayName(for level: MembershipLevel) -> String {
        return level.rawValue
    }
    
    private func membershipEnglishName(for level: MembershipLevel) -> String {
        return level.englishName
    }
    
    private func nextMembershipLevel(current: MembershipLevel) -> MembershipLevel? {
        switch current {
        case .lv1:
            return .lv2
        case .lv2:
            return .lv3
        case .lv3:
            return .lv4
        case .lv4:
            return nil
        }
    }
    
    private func requiredPointsForNextLevel(current: MembershipLevel) -> Int {
        switch current {
        case .lv1:
            return MembershipLevel.lv2.pointsRequired
        case .lv2:
            return MembershipLevel.lv3.pointsRequired
        case .lv3:
            return MembershipLevel.lv4.pointsRequired
        case .lv4:
            return MembershipLevel.lv4.pointsRequired
        }
    }
    
    private func formatJoinDate(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = dataManager.currentLanguage == "zh" ? "yyyy年MM月" : "MMM yyyy"
        return formatter.string(from: date)
    }
    
    private func formatJoinDateWithDay(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = dataManager.currentLanguage == "zh" ? "yyyy年MM月dd日" : "MMM dd, yyyy"
        return formatter.string(from: date)
    }
    
    // MARK: - 进度条宽度计算
    private func progressWidth(for user: User, totalWidth: CGFloat) -> CGFloat {
        let userPoints = user.totalPointsEarned
        
        // 定义等级门槛
        let level1Threshold = 200  // Neon Rookie -> Hype Blaze
        let level2Threshold = 800  // Hype Blaze -> Vibe Regent
        let level3Threshold = 1600 // Vibe Regent -> Aureus Legend
        
        // 计算进度条的三个区间，每个区间占总宽度的1/3
        let sectionWidth = totalWidth / 3.0
        
        if userPoints <= level1Threshold {
            // 在第一个区间内
            let progress = Double(userPoints) / Double(level1Threshold)
            return sectionWidth * CGFloat(progress)
        } else if userPoints <= level2Threshold {
            // 在第二个区间内
            let progress = Double(userPoints - level1Threshold) / Double(level2Threshold - level1Threshold)
            return sectionWidth + (sectionWidth * CGFloat(progress))
        } else if userPoints <= level3Threshold {
            // 在第三个区间内
            let progress = Double(userPoints - level2Threshold) / Double(level3Threshold - level2Threshold)
            return (sectionWidth * 2) + (sectionWidth * CGFloat(progress))
        } else {
            // 超过最高等级，显示满进度条
            return totalWidth
        }
    }

}



// MARK: - 菜单项按钮
struct MenuItemButton: View {
    let icon: String
    let title: String
    let subtitle: String
    let action: () -> Void
    let gradientColors: [Color]
    let iconColor: Color
    
    init(icon: String, title: String, subtitle: String, action: @escaping () -> Void, gradientColors: [Color] = [
        Color(red: 0.35, green: 0.25, blue: 0.30),
        Color(red: 0.25, green: 0.15, blue: 0.20),
        Color(red: 0.15, green: 0.05, blue: 0.10)
    ], iconColor: Color = Color(red: 1.0, green: 0.6, blue: 0.2)) {
        self.icon = icon
        self.title = title
        self.subtitle = subtitle
        self.action = action
        self.gradientColors = gradientColors
        self.iconColor = iconColor
    }
    
    var body: some View {
        Button(action: action) {
            VStack(spacing: 12) {
                Image(systemName: icon)
                    .font(.title2)
                    .foregroundColor(iconColor)
                
                VStack(spacing: 4) {
                    Text(title)
                        .font(.subheadline)
                        .fontWeight(.medium)
                        .foregroundColor(.white)
                    
                    Text(subtitle)
                        .font(.caption)
                        .foregroundColor(Color(red: 1.0, green: 0.5, blue: 0.0)) // 深橙色
                }
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, 20)
            .background(
                RoundedRectangle(cornerRadius: 15)
                    .fill(
                        LinearGradient(
                            colors: gradientColors,
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .overlay(
                        RoundedRectangle(cornerRadius: 15)
                            .stroke(
                                LinearGradient(
                                    colors: [
                                        Color.white.opacity(0.2),
                                        Color.clear
                                    ],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                ),
                                lineWidth: 1
                            )
                    )
                    .shadow(color: Color.black.opacity(0.3), radius: 8, x: 0, y: 4)
            )
        }
        .buttonStyle(PlainButtonStyle())
    }
}

// MARK: - 特权行
struct BenefitRow: View {
    let icon: String
    let title: String
    let description: String
    
    var body: some View {
        HStack(spacing: 15) {
            // 图标容器，增加3D效果
            ZStack {
                Circle()
                    .fill(
                        LinearGradient(
                            colors: [
                                Color(red: 1.0, green: 0.7, blue: 0.3),
                                Color(red: 1.0, green: 0.5, blue: 0.1)
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .frame(width: 40, height: 40)
                    .shadow(color: Color(red: 1.0, green: 0.5, blue: 0.1).opacity(0.4), radius: 6, x: 0, y: 3)
                
                Image(systemName: icon)
                    .font(.title3)
                    .foregroundColor(.white)
                    .font(.system(size: 18, weight: .semibold))
            }
            
            VStack(alignment: .leading, spacing: 4) {
                Text(title)
                    .font(.system(size: 15, weight: .semibold))
                    .foregroundColor(.white)
                
                Text(description)
                    .font(.caption)
                    .foregroundColor(.white.opacity(0.85))
                    .lineLimit(2)
            }
            
            Spacer()
            
            // 右侧装饰箭头
            Image(systemName: "chevron.right")
                .font(.caption)
                .foregroundColor(.white.opacity(0.6))
        }
        .padding(18)
        .background(
            ZStack {
                // 主背景渐变
                RoundedRectangle(cornerRadius: 16)
                    .fill(
                        LinearGradient(
                            colors: [
                                Color(red: 0.35, green: 0.35, blue: 0.4),
                                Color(red: 0.25, green: 0.25, blue: 0.3),
                                Color(red: 0.2, green: 0.2, blue: 0.25)
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                
                // 内部高光效果
                RoundedRectangle(cornerRadius: 16)
                    .fill(
                        LinearGradient(
                            colors: [
                                Color.white.opacity(0.1),
                                Color.clear,
                                Color.clear
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
            }
        )
        .overlay(
            RoundedRectangle(cornerRadius: 16)
                .stroke(
                    LinearGradient(
                        colors: [
                            Color.white.opacity(0.3),
                            Color.white.opacity(0.1),
                            Color.clear
                        ],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    ),
                    lineWidth: 1.5
                )
        )
        .shadow(color: Color.black.opacity(0.4), radius: 12, x: 0, y: 6)
        .shadow(color: Color.black.opacity(0.2), radius: 4, x: 0, y: 2)
    }
}

// MARK: - 我的优惠券视图
struct MyCouponsView: View {
    @EnvironmentObject var dataManager: DataManager
    @Environment(\.presentationMode) var presentationMode
    @State private var selectedCoupon: Coupon?
    
    enum CouponStatus {
        case available
        case expired
        case usedOnce
        case usedThisWeek
        case usedToday
        case usedThisMonth
        case usedThisYear
        case outsideTimeSlot
        case notActivated
        case requiresLogin
        case requiresMembershipLevel
    }
    
    private func checkCouponActivation(coupon: Coupon) -> CouponStatus {
        // 首先检查周频率优惠券的使用状态
        if coupon.usageFrequency == .weekly, let user = dataManager.currentUser {
            let calendar = Calendar.current
            if let currentWeekInterval = calendar.dateInterval(of: .weekOfYear, for: Date()) {
                // 检查本周是否已使用过此优惠券
                let usedThisWeek = user.couponUsageHistory.contains { record in
                    record.couponCode == coupon.code &&
                    currentWeekInterval.contains(record.usedDate)
                }
                
                // 如果本周已使用，返回usedThisWeek状态
                if usedThisWeek {
                    return .usedThisWeek
                }
            }
        }
        
        let unlockCondition = CouponConfig.UnlockConditions.getUnlockConditionType(
            for: coupon.code,
            user: dataManager.currentUser,
            dataManager: dataManager
        )
        
        switch unlockCondition {
        case .loginRequired:
            return .requiresLogin
        case .membershipLevel(_):
            return .requiresMembershipLevel
        case .timeSlotRestricted:
            return .outsideTimeSlot
        case .memberInfoComplete, .birthdayMonthRequired, .activationConditions(_), .expired, .inactive:
            return .notActivated
        case .usageLimitReached:
            return .usedOnce
        case .usageFrequencyReached:
            // 根据使用频率返回相应状态
            if let frequency = coupon.usageFrequency {
                switch frequency {
                case .once:
                    return .usedOnce
                case .daily:
                    return .usedToday
                case .weekly:
                    return .usedThisWeek
                case .monthly:
                    return .usedThisMonth
                case .yearly:
                    return .usedThisYear
                case .perOrder:
                    return .usedOnce
                }
            }
            return .usedOnce
        case .none:
            return .available
        }
    }
    
    var availableCoupons: [Coupon] {
        return dataManager.getAllCouponsForDisplay()
    }
    
    var sortedAvailableCoupons: [Coupon] {
        return dataManager.getSortedAvailableCoupons()
    }
    
    var body: some View {
        ZStack {
            // 背景渐变 - 与 All Coupons 保持一致
            LinearGradient(
                colors: [
                    Color(red: 0.05, green: 0.05, blue: 0.1),
                    Color(red: 0.1, green: 0.1, blue: 0.15),
                    Color(red: 0.08, green: 0.08, blue: 0.12)
                ],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .ignoresSafeArea()
            
            VStack(spacing: 0) {
                // 自定义导航栏 - 与 All Coupons 保持一致
                HStack {
                    Button(action: { 
                        presentationMode.wrappedValue.dismiss()
                    }) {
                        Image(systemName: "chevron.left")
                            .font(.system(size: 18, weight: .medium))
                            .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                    }
                    
                    Spacer()
                    
                    Button(dataManager.currentLanguage == "zh" ? "完成" : "Done") {
                        presentationMode.wrappedValue.dismiss()
                    }
                    .foregroundColor(.white)
                }
                .padding(.horizontal, 20)
                .padding(.top, 8)
                .padding(.bottom, 4)
                
                // 主要内容区域
                ZStack {
                    ScrollView {
                        VStack(spacing: 16) {
                            // 页面标题 - 与 All Coupons 保持一致
                            HStack {
                                VStack(alignment: .leading, spacing: 6) {
                                    Text(dataManager.currentLanguage == "zh" ? "我的优惠券" : "My Coupons")
                                        .font(.title)
                                        .fontWeight(.bold)
                                        .foregroundColor(.white)
                                    
                                    Text(dataManager.currentLanguage == "zh" ? "选择您喜欢的优惠券" : "Choose your favorite coupons")
                                        .font(.subheadline)
                                        .foregroundColor(.white.opacity(0.8))
                                }
                                
                                Spacer()
                            }
                            .padding(.horizontal, 20)
                            .padding(.top, 8)
                            
                            // 优惠券网格 - 与 All Coupons 保持一致
                            LazyVGrid(columns: [
                                GridItem(.flexible())
                            ], spacing: 8) {
                                ForEach(sortedAvailableCoupons, id: \.id) { coupon in
                                    myCouponCard(coupon: coupon)
                                        .scaleEffect(1.0)
                                        .animation(.spring(response: 0.5, dampingFraction: 0.7, blendDuration: 0), value: coupon.id)
                                        .onTapGesture {
                                            selectedCoupon = coupon
                                        }
                                }
                            }
                            .padding(.horizontal, 20)
                        }
                        .padding(.bottom, 30)
                    }
                }
            }
        }
        .sheet(item: $selectedCoupon) { coupon in
            if #available(iOS 16.0, *) {
                CouponDetailSheet(coupon: coupon)
                    .environmentObject(dataManager)
            } else {
                Text("详细信息")
                    .padding()
            }
        }
    }
     
     // 我的优惠券卡片 - 与 All Coupons 样式保持一致
     func myCouponCard(coupon: Coupon) -> some View {
         let isCashVoucher = coupon.isCashVoucher
         let displayTitle = coupon.formattedTitle(language: dataManager.currentLanguage)
         let quantity = isCashVoucher ? dataManager.getCashVoucherQuantityByTitle(coupon.title) : nil
         
         // 使用统一的解锁检查逻辑
         let isUnlocked = dataManager.isUserCouponUnlocked(coupon)
         let activationStatus = checkCouponActivation(coupon: coupon)
         let isNotActivated = activationStatus != .available
         
         // 检查会员信息完善礼券的特殊状态（与All Coupons保持一致）
         let isMemberInfoCoupon = coupon.code == "MEMBER_INFO_COMPLETE"
         let isDisabled = isMemberInfoCoupon && !(dataManager.currentUser?.isMemberInfoComplete ?? false)
         let hasUserCoupon = dataManager.currentUser?.ownedCoupons.contains { $0.couponCode == coupon.code && !$0.isUsed && $0.expiryDate > Date() } ?? false
         
         // 检查是否因为非运营时间而被限制
         let isTimeSlotRestricted = activationStatus == .outsideTimeSlot
         
         // 如果是会员信息完善礼券且用户已拥有，则显示为可用状态
         // 如果用户未解锁此优惠券，则显示为禁用状态
         // 但如果仅仅是因为非运营时间限制，则在视觉上不显示为禁用状态
         let finalDisabled = !isUnlocked || (isMemberInfoCoupon ? (!hasUserCoupon && isDisabled) : (isNotActivated && !isTimeSlotRestricted))
         
         let baseCard = myCouponCardView(
             tag: coupon.formatValue(),
             tagColor: CouponTheme.getTagBackgroundColor(for: coupon.title),
             tagTextColor: CouponTheme.getTagTextColor(for: coupon.title),
             buttonColor: CouponTheme.getButtonBackgroundColor(for: coupon.title),
             buttonTextColor: CouponTheme.getButtonTextColor(for: coupon.title),
             value: coupon.formatValue(),
             title: coupon.formattedRemarks(language: dataManager.currentLanguage, displayTitle: displayTitle),
             validUntil: isUnlocked ? coupon.formatStaticValidUntil(language: dataManager.currentLanguage) : getUnlockConditionText(for: coupon),
             gradientColors: CouponTheme.getGradientColors(for: coupon.title),
             showStrikethrough: finalDisabled,
             isDisabled: finalDisabled,
             quantity: quantity,
             originalTitle: coupon.title,
             onButtonTap: {
                 handleButtonTap(for: coupon)
             }
         )
         
         // 统一所有锁定状态的视觉样式：如果优惠券被锁定（未解锁或未激活），都添加覆盖层
         if finalDisabled {
             return AnyView(myLockedCouponCard(baseCard: baseCard, coupon: coupon, activationStatus: activationStatus, isUnlocked: isUnlocked))
         } else {
             return AnyView(baseCard)
         }
     }
     
     // 统一的锁定优惠券卡片覆盖层
     func myLockedCouponCard(baseCard: some View, coupon: Coupon, activationStatus: CouponStatus, isUnlocked: Bool) -> some View {
         let statusText: String
         let statusTextEn: String
         
         // 统一的锁定原因显示逻辑
         if !isUnlocked {
             // 未解锁状态 - 统一显示解锁条件
             if coupon.requiresLogin && dataManager.currentUser == nil {
                 statusText = "需要登录"
                 statusTextEn = "Login Required"
             } else if let requiredLevelString = coupon.requiresMembershipLevel {
                 // 根据requiresMembershipLevel（英文名称）找到对应的中文显示名称
                 let displayName = MembershipLevel.getDisplayName(for: requiredLevelString, language: "zh") ?? requiredLevelString
                 let englishName = MembershipLevel.getDisplayName(for: requiredLevelString, language: "en") ?? requiredLevelString
                 statusText = "需要 \(displayName) 会员等级"
                 statusTextEn = "Requires \(englishName) Membership"
             } else if coupon.code == "BIRTHDAY30" || coupon.code == "MEMBER_INFO_COMPLETE" {
                 // 生日月专属礼券和会员信息完善礼券需要完善会员信息后才能解锁
                 statusText = "完善会员信息后才能解锁"
                 statusTextEn = "Complete member info to unlock"
             } else {
                 // 统一显示：注册成为会员即可解锁
                 statusText = "注册成为会员即可解锁"
                 statusTextEn = "Register as member to unlock"
             }
         } else {
             // 已解锁但未激活状态 - 显示激活条件
             switch activationStatus {
             case .requiresLogin:
                 statusText = "需要登录"
                 statusTextEn = "Login Required"
             case .requiresMembershipLevel:
                 if let requiredLevel = coupon.requiresMembershipLevel {
                     // 根据requiresMembershipLevel（英文名称）找到对应的中文显示名称
                     if let membershipLevel = MembershipLevel.allCases.first(where: { $0.rawValue == requiredLevel }) {
                         let displayName = membershipLevel.displayName
                         let englishName = membershipLevel.englishDisplayName
                         statusText = "需要 \(displayName) 会员等级"
                         statusTextEn = "Requires \(englishName) Membership"
                     } else {
                         statusText = "需要 \(requiredLevel) 会员等级"
                         statusTextEn = "Requires \(requiredLevel) Membership"
                     }
                 } else {
                     statusText = "需要更高会员等级"
                     statusTextEn = "Higher membership level required"
                 }
             case .outsideTimeSlot:
                     statusText = "不在运营时间，无法应用"
                     statusTextEn = "Outside business hours"
             case .usedThisWeek:
                 statusText = "本周已用，下周自动解锁"
                 statusTextEn = "Used this week, will unlock next week"
             case .notActivated:
                 if let conditions = coupon.activationConditions {
                     statusText = conditions
                 } else {
                     statusText = "未激活"
                 }
                 if let conditionsEn = coupon.englishActivationConditions {
                     statusTextEn = conditionsEn
                 } else {
                     statusTextEn = "Not Activated"
                 }
             default:
                 statusText = "未激活"
                 statusTextEn = "Not Activated"
             }
         }
         
         return ZStack {
             baseCard
                 .opacity(0.6)
             
             // 统一的黑色半透明覆盖层
             RoundedRectangle(cornerRadius: 16)
                 .fill(Color.black.opacity(0.3))
                 .overlay(
                     VStack(spacing: 8) {
                         Image(systemName: "lock.fill")
                             .font(.system(size: 24))
                             .foregroundColor(.white)
                         
                         Text(dataManager.currentLanguage == "zh" ? statusText : statusTextEn)
                             .font(.system(size: 14, weight: .medium))
                             .foregroundColor(.white)
                             .multilineTextAlignment(.center)
                             .padding(.horizontal, 16)
                     }
                 )
         }
     }
     
     // 处理按钮点击
     func handleButtonTap(for coupon: Coupon) {
         // 检查是否是会员信息完善礼券
         if coupon.code == "MEMBER_INFO_COMPLETE" {
             let hasUserCoupon = dataManager.currentUser?.ownedCoupons.contains { $0.couponCode == coupon.code && !$0.isUsed && $0.expiryDate > Date() } ?? false
             let isMemberInfoComplete = dataManager.currentUser?.isMemberInfoComplete ?? false
             
             if !hasUserCoupon && !isMemberInfoComplete {
                 // 如果用户没有完善信息，显示提示
                 return
             }
         }
         
         // 所有优惠券都显示详情弹窗
         selectedCoupon = coupon
     }
     

     


     
     // 获取按钮文本
     func getButtonTextForCard(for title: String, isDisabled: Bool) -> String {
         if isDisabled {
             return dataManager.currentLanguage == "zh" ? "不可用" : "Unavailable"
         } else {
             return dataManager.currentLanguage == "zh" ? "查看详情" : "View Details"
         }
     }
     
     // 获取解锁条件文本
     func getUnlockConditionText(for coupon: Coupon) -> String {
         let isLoggedIn = dataManager.currentUser != nil
         
         if !isLoggedIn {
             return dataManager.currentLanguage == "zh" ? "需要登录" : "Login Required"
         }
         
         if let requiredLevelString = coupon.requiresMembershipLevel, !requiredLevelString.isEmpty {
             // 根据requiresMembershipLevel（英文名称）找到对应的显示名称
             if let membershipLevel = MembershipLevel.allCases.first(where: { $0.rawValue == requiredLevelString }) {
                 let displayName = membershipLevel.displayName
                 let englishName = membershipLevel.englishDisplayName
                 return dataManager.currentLanguage == "zh" ? "需要 \(displayName) 会员" : "Requires \(englishName) Membership"
             } else {
                 return dataManager.currentLanguage == "zh" ? "需要 \(requiredLevelString) 会员" : "Requires \(requiredLevelString) Membership"
             }
         }
         
         switch coupon.code {
         case "FUELUP_STREAK":
             return dataManager.currentLanguage == "zh" ? "需要连续签到" : "Requires Check-in Streak"
         case "WEEKEND50":
             return dataManager.currentLanguage == "zh" ? "仅限周末" : "Weekend Only"
         case "HIGHBALL":
             return dataManager.currentLanguage == "zh" ? "需要特定条件" : "Special Conditions Required"
         default:
             return dataManager.currentLanguage == "zh" ? "需要满足条件" : "Conditions Required"
         }
     }
 
     @ViewBuilder
      func myCouponCardView(
          tag: String,
          tagColor: Color,
          tagTextColor: Color,
          buttonColor: Color,
          buttonTextColor: Color,
          value: String,
          title: String,
          validUntil: String,
          gradientColors: [Color],
          showStrikethrough: Bool = false,
          isDisabled: Bool = false,
          quantity: Int? = nil,
          originalTitle: String,
          onButtonTap: (() -> Void)? = nil
     ) -> some View {
         
         let buttonBackgroundView: some View = ZStack {
             // 3D立体效果背景
             Capsule()
                 .fill(buttonColor)
                 .shadow(color: .black.opacity(0.3), radius: 2, x: 0, y: 2)
                 .overlay(
                     Capsule()
                         .stroke(
                             LinearGradient(
                                 colors: [
                                     Color.white.opacity(0.8),
                                     Color.clear
                                 ],
                                 startPoint: .top,
                                 endPoint: .bottom
                             ),
                             lineWidth: 0.5
                         )
                 )
             
             // 内部高光效果
             Capsule()
                 .fill(
                     LinearGradient(
                         colors: [
                             Color.white.opacity(0.3),
                             Color.clear
                         ],
                         startPoint: .top,
                         endPoint: .center
                     )
                 )
                 .frame(height: 8)
                 .offset(y: -2)
         }
         
         VStack(alignment: .leading, spacing: 3) {
             HStack {
                 HStack(spacing: 4) {
                     Text(tag)
                         .font(.caption2)
                         .fontWeight(.bold)
                         .foregroundColor(tagTextColor)
                         .padding(.horizontal, 4)
                         .padding(.vertical, 1)
                         .background(Capsule().fill(tagColor))
                     
                     // 根据配置决定特定现金券的徽章位置
                     let shouldShowBadgeAdjacentToTag = AppConfig.CashVoucher.Layout.specificVoucherBadgePositions[tag] == .adjacentToTag || 
                                                       AppConfig.CashVoucher.Layout.specificVoucherBadgePositions[originalTitle] == .adjacentToTag
                     
                     // 调试信息：打印实际的tag和originalTitle值
                     let _ = {
                         if originalTitle.contains("Cash Voucher") || originalTitle.contains("现金券") {
                             // 我的优惠券现金券徽章位置计算
                         }
                     }()
                     
                     // 如果配置为紧邻标签显示，则在这里显示数量徽章
                     if let quantity = quantity, quantity > 0, shouldShowBadgeAdjacentToTag {
                         Text("\(quantity)")
                             .font(.caption2)
                             .fontWeight(.bold)
                             .foregroundColor(.white)
                             .padding(AppConfig.CashVoucher.Layout.quantityBadgeSize)
                             .background(
                                 Circle()
                                     .fill(
                                         LinearGradient(
                                             colors: [
                                                 Color.red,
                                                 Color.red.opacity(0.8)
                                             ],
                                             startPoint: .top,
                                             endPoint: .bottom
                                         )
                                     )
                                     .shadow(color: .black.opacity(0.3), radius: 2, x: 0, y: 1)
                             )
                     }
                 }
                 
                 Spacer()
                 
                 // 特定现金券金额文字特殊处理：向左偏移避免被数字标识遮挡，并右对齐
                 let shouldOffsetValueText = AppConfig.CashVoucher.Layout.specificVoucherBadgePositions[tag] == .adjacentToTag || 
                                            AppConfig.CashVoucher.Layout.specificVoucherBadgePositions[originalTitle] == .adjacentToTag
                 
                 // 调试信息：打印右上角徽章的相关信息
                 let _ = {
                     if originalTitle.contains("Cash Voucher") || originalTitle.contains("现金券") {
                         // 我的优惠券右侧徽章位置计算
                     }
                 }()
                 
                 Text(value)
                     .font(.title2)
                     .fontWeight(.bold)
                     .foregroundColor(.white)
                     .strikethrough(showStrikethrough, color: .white)
                     .multilineTextAlignment(.trailing) // 右对齐
                     .offset(x: shouldOffsetValueText ? AppConfig.CashVoucher.Layout.valueTextLeftOffset : 0) // 为特定现金券向左偏移
             }
             
             Text(title)
                 .font(.caption2)
                 .fontWeight(.semibold)
                 .foregroundColor(.white)
                 .lineLimit(1)
                 .multilineTextAlignment(.leading)
             
             VStack(alignment: .leading, spacing: 2) {
                 HStack {
                     Text(validUntil)
                         .font(.caption2)
                         .foregroundColor(.white.opacity(0.8))
                         .lineLimit(1)
                     
                     Spacer()
                     
                     Button(action: {
                         onButtonTap?()
                     }) {
                         Text(getButtonTextForCard(for: title, isDisabled: isDisabled))
                             .font(.caption2)
                             .fontWeight(.bold)
                             .foregroundColor(buttonTextColor)
                             .padding(.horizontal, 8)
                             .padding(.vertical, 3)
                             .background(buttonBackgroundView)
                     }
                     .disabled(isDisabled)
                     .scaleEffect(isDisabled ? 0.9 : 1.0)
                     .opacity(isDisabled ? 0.6 : 1.0)
                 }
             }
         }
         .padding(8)
         .frame(height: 76) // 统一高度与HomeView保持一致
         .frame(maxWidth: .infinity)
         .background(
             ZStack {
                 // 主背景渐变
                 RoundedRectangle(cornerRadius: 12)
                     .fill(
                         LinearGradient(
                             colors: isDisabled ? [Color.gray.opacity(0.6), Color.gray.opacity(0.4)] : gradientColors,
                             startPoint: .topLeading,
                             endPoint: .bottomTrailing
                         )
                     )
                 
                 // 3D立体效果
                 RoundedRectangle(cornerRadius: 12)
                     .stroke(
                         LinearGradient(
                             colors: [
                                 Color.white.opacity(0.3),
                                 Color.clear,
                                 Color.black.opacity(0.1)
                             ],
                             startPoint: .topLeading,
                             endPoint: .bottomTrailing
                         ),
                         lineWidth: 1
                     )
                 
                 // 内部高光
                 RoundedRectangle(cornerRadius: 11)
                     .fill(
                         LinearGradient(
                             colors: [
                                 Color.white.opacity(0.15),
                                 Color.clear
                             ],
                             startPoint: .top,
                             endPoint: .center
                         )
                     )
                     .padding(1)
             }
             .shadow(color: .black.opacity(0.2), radius: 6, x: 0, y: 3)
             .shadow(color: .black.opacity(0.1), radius: 2, x: 0, y: 1)
         )
         .overlay(
             // 数量角标（仅对非特定现金券显示在右上角）
             Group {
                 if let quantity = quantity, quantity > 0 {
                     // 计算徽章显示位置
                     let shouldShowInTopRight = AppConfig.CashVoucher.Layout.specificVoucherBadgePositions[tag] != .adjacentToTag && 
                                               AppConfig.CashVoucher.Layout.specificVoucherBadgePositions[originalTitle] != .adjacentToTag
                     
                     if shouldShowInTopRight {
                         VStack {
                             HStack {
                                 Spacer()
                                 Text("\(quantity)")
                                     .font(.caption2)
                                     .fontWeight(.bold)
                                     .foregroundColor(.white)
                                     .padding(AppConfig.CashVoucher.Layout.quantityBadgeSize)
                                     .background(
                                         Circle()
                                             .fill(
                                                 LinearGradient(
                                                     colors: [
                                                         Color.red,
                                                         Color.red.opacity(0.8)
                                                     ],
                                                     startPoint: .top,
                                                     endPoint: .bottom
                                                 )
                                             )
                                             .shadow(color: .black.opacity(0.3), radius: 2, x: 0, y: 1)
                                     )
                                     .offset(x: AppConfig.CashVoucher.Layout.quantityBadgeRightOffset, y: AppConfig.CashVoucher.Layout.quantityBadgeTopOffset)
                             }
                             Spacer()
                         }
                     }
                 }
             }
         )
         .opacity(isDisabled ? 0.7 : 1.0)
     }
}
 


#Preview {
    MeView()
        .environmentObject(DataManager.shared)
}